package com.md.api.service.impl;

import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.md.api.common.config.RedisKeys;
import com.md.api.common.exception.BusinessException;
import com.md.api.common.utils.*;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.constants.SysConstants;
import com.md.api.entity.dto.ComposeCommitDto;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.dto.SendDto;
import com.md.api.entity.enums.*;
import com.md.api.entity.util.Page;
import com.md.api.service.SysUserSevice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static sun.security.krb5.Confounder.intValue;

/**
 * @Author liujie
 * @ClassName UserServiceImpl
 * @Date 2022年11月09日11:35
 **/

@Slf4j
@Service
public class SysUserServiceImpl implements SysUserSevice {
    @Value("${wx.pay.backShoppingNotifyUrl}")
    private String backShoppingNotifyUrl;
    @Value("${wx.pay.backMotNotifyUrl}")
    private String backMotNotifyUrl;
    @Resource
    private WxPayService wxService;
    @Resource
    UserMessageMapper userMessageMapper;
    @Resource
    UserBalanceRecordMapper balanceRecordMapper;
    @Resource
    RechargeOrderMapper rechargeOrderMapper;
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    MotOrderMapper motOrderMapper;
    @Resource
    MotReservationMapper reservationMapper;
    @Resource
    ShoppingOrderMapper shoppingOrderMapper;
    @Resource
    ShoppingOrderDetailMapper shoppingOrderDetailMapper;
    @Resource
    ShoppingRefundOrderMapper shoppingRefundOrderMapper;
    @Resource
    ShoppingChangeOrderMapper changeOrderMapper;
    @Resource
    UserWithdrawalRecordMapper withdrawalRecordMapper;
    @Resource
    ShoppingSkuMapper shoppingSkuMapper;
    @Resource
    CarFirstAidMapper carFirstAidMapper;
    @Resource
    CarDefaultImgMapper carDefaultImgMapper;
    @Resource
    ShoppingSpuMapper shoppingSpuMapper;
    @Resource
    ShopLocationMapper locationMapper;
    @Resource
    AdvertisementInfoMapper advertisementInfoMapper;
    @Resource
    RedisUtil redisUtil;
    @Resource
    UserMapper userMapper;
    @Resource
    ReceivingAddrInfoMapper addrInfoMapper;
    @Resource
    IndexMapper indexMapper;
    @Value("${common-key}")
    String commonKey;
    @Resource
    SysCarTypeMapper carTypeMapper;
    @Resource
    SiteInfoMapper siteMapper;
    @Resource
    UserCarMapper userCarMapper;
    @Resource
    SiteServiceContentMapper serviceContentMapper;
    @Resource
    ShoppingSpuTypeMapper shoppingSpuTypeMapper;
    @Resource
    CouponInfoMapper couponMapper;
    @Resource
    UserCouponRecordMapper couponRecordMapper;
    @Resource
    UserPointRecordMapper pointRecordMapper;
    @Resource
    private ExeclUploadUtils execlUploadUtils;
    @Resource
    SiteServicePredetermineRecordMapper predetermineRecordMapper;
    @Value("${excel.file.root.path}")
    private String FILE_PATH;
    @Override
    public HttpResult indexCount() {
        Map<String,Object> map = new HashMap<>();

        map.put("todayShoppingOrder",indexMapper.getShoppingOrderCount("today"));
        map.put("allShoppingOrder",indexMapper.getShoppingOrderCount("all"));

        map.put("todayMotOrder",indexMapper.getMotOrderCount("today"));
        map.put("allMotOrder",indexMapper.getMotOrderCount("all"));

        map.put("todayMotMoney",indexMapper.getMotOrderMoney("today"));
        map.put("allMotMoney",indexMapper.getMotOrderMoney("all"));


        map.put("todayReservationOrder",indexMapper.getReservationCount("today"));
        map.put("allReservationOrder",indexMapper.getReservationCount("all"));

        map.put("waitMotWriteOff",indexMapper.waitMotWriteOff());

        map.put("userTodayCount",indexMapper.getUserCount("today"));
        map.put("userAllCount",indexMapper.getUserCount("all"));

        map.put("shoppingLowCount",shoppingSkuMapper.getLowCount(null));
        map.put("waitShoppingRefundCount",shoppingRefundOrderMapper.waitRefund());


        return new HttpResult(map);
    }

    @Override
    public HttpResult addUser( SysUser user) {
        try {
            SysUser dbuser = sysUserMapper.findByUserName(user.getUserName(),null);
            if (dbuser!=null){
                return HttpResult.fail("该用户名已被使用！");
            }
            String aesKey = AESUtil.randomCode();
            user.setUserRole(user.getUserRole());
            user.setAesKey(aesKey);
            user.setPassword(AESUtil.encrypt(user.getPassword(),aesKey));
            sysUserMapper.addUser(user);
        }catch (Exception e){
            e.printStackTrace();
            return HttpResult.fail("注册失败！");
        }
        return HttpResult.OK;
    }
    @Override
    public HttpResult updateUser( SysUser user) {
        sysUserMapper.updateUser(user);
        return HttpResult.OK;
    }

    @Override
    public HttpResult updatePass( SysUser user) {
        SysUser dbUser = sysUserMapper.getById(user.getUserId());
        String encrypt = AESUtil.decrypt(user.getOriginalPassword(), commonKey);
        if (!AESUtil.encrypt(encrypt,dbUser.getAesKey()).equalsIgnoreCase(dbUser.getPassword())){
            return HttpResult.fail("原密码错误，请确认！");
        }
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String newEncrypt = AESUtil.decrypt(user.getPassword(), commonKey);
            user.setPassword(AESUtil.encrypt(newEncrypt,dbUser.getAesKey()));
        }
        sysUserMapper.updatePass(user);
        return HttpResult.OK;
    }

    @Override
    public HttpResult sysUserLogin( SysUser user) {
        try {
            SysUser dbuser = sysUserMapper.findByUserName(user.getUserName(),0);
            if (null==dbuser){
                return HttpResult.fail("未查询到该账号！");
            }
            String encrypt = AESUtil.decrypt(user.getPassword(), commonKey);
            String aesKey = dbuser.getAesKey();
            if (!AESUtil.encrypt(encrypt,aesKey).equalsIgnoreCase(dbuser.getPassword())){
                return HttpResult.fail("账号或密码错误，请确认！");
            }
            String loginToken = UUID.randomUUID().toString().replaceAll("-", "");
            dbuser.setToken(loginToken);
            dbuser.setPassword(null);
            dbuser.setAesKey(null);
            redisUtil.set(RedisKeys.getSysUserTokenInfoKey(loginToken),dbuser,3600*24);
            return new HttpResult(dbuser);
        }catch (Exception e){
            e.printStackTrace();
            return HttpResult.fail("登录失败！");
        }
    }



    @Override
    public HttpResult resetPass( SysUser sysUser) {
        SysUser dbUser = sysUserMapper.getById(sysUser.getUserId());
        dbUser.setPassword(AESUtil.encrypt("123456",dbUser.getAesKey()));
        sysUserMapper.updatePass(dbUser);
//        sysUserMapper.resetPass(commitDto.getUserIds(),DescUtil.encrypt("123456"));
        return HttpResult.OK;
    }

    @Override
    public HttpResult bindSite(SysUser user) {
        sysUserMapper.bindSite(user);
        return HttpResult.OK;
    }

    @Override
    public HttpResult userPage(ComposeQueryDto compose){
            Page page = compose.getPage();
        try {
            page.initPagingData(SysUser.class);
            List<SysUser> userList= sysUserMapper.userPage(compose.getUserName(),compose.getNickName(),compose.getStatus());
//            for (SysUser user:userList){
//                user.setPassword(DescUtil.decryptor(user.getPassword()));
//            }
            page.setResult(userList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new HttpResult(page);
    }

    @Override
    public HttpResult deleteUser( ComposeCommitDto commitDto) {
        sysUserMapper.deleteUser(commitDto.getUserIds());
        return HttpResult.OK;
    }

    @Override
    public HttpResult enableUser( SysUser user) {
        sysUserMapper.updateUserStatus(user);
        return HttpResult.OK;
    }



    @Override
    public HttpResult shoppingSpuPage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingSpu.class);
        List<ShoppingSpu> spuList = shoppingSpuMapper.sysList(qto.getKeyword(),qto.getDrinkingType(), qto.getStatus());
        for (ShoppingSpu spu:spuList){
            int count = shoppingSkuMapper.getLowCount(spu.getSpuId());
            spu.setLowCount(count);
        }
        page.setResult(spuList);
        return new HttpResult(page);
    }

    @Override
    public HttpResult shoppingSkuPage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingSku.class);
        List<ShoppingSku> skuList = shoppingSkuMapper.getBySpuId(qto.getSpuId());
        page.setResult(skuList);
        return new HttpResult(page);
    }

    @Override
    public HttpResult rechargeOrderPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(RechargeOrder.class);
        List<RechargeOrder> list = rechargeOrderMapper.sysList(null,qto.getPayStatus(),qto.getOrderType(),qto.getPayType(),qto.getPayTimeStart(),qto.getPayTimeEnd());
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult motOrderPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(MotOrder.class);
        List<MotOrder> list = motOrderMapper.list(null,qto.getSiteId(),qto.getIsWriteOff(), qto.getMotType(),
                        qto.getStatus(),qto.getPayTimeStart(),qto.getPayTimeEnd(),qto.getSiteName());
        for (MotOrder order:list){
            order.setCar(userCarMapper.getByCarId(order.getCarId()));
//            order.setServiceContent(serviceContentMapper.getByServiceId(order.getServiceId()));
//            order.setSiteInfo(siteMapper.getBySiteId(order.getSiteId()));
        }
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult cancelMotOrder(MotOrder order) {
        MotOrder motOrder = motOrderMapper.getByMotNo(order.getMotNo());
        if (motOrder.getStatus()!=MotOrderStatus.PAYING.value()){
            return HttpResult.fail("订单状态有误！");
        }
        motOrder.setStatus(MotOrderStatus.CANCEL.value());
        motOrderMapper.updateOrder(motOrder);
        return HttpResult.OK;
    }

    @Override
    public HttpResult motSiteOrderPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(MotOrder.class);
        List<MotOrder> list = motOrderMapper.siteList(null,qto.getSiteId(),qto.getIsWriteOff(), qto.getMotType(),
                qto.getStatus(),qto.getPayTimeStart(),qto.getPayTimeEnd());
        for (MotOrder order:list){
            order.setCar(userCarMapper.getByCarId(order.getCarId()));
            order.setServiceContent(serviceContentMapper.getByServiceId(order.getServiceId()));
        }
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult writeOffMotOrder(MotOrder order) {

        MotOrder dbOrder = motOrderMapper.getByMotNo(order.getMotNo());
        if (null==dbOrder){
            return HttpResult.fail("暂无该订单信息！");
        }
        if (dbOrder.getIsWriteOff()==2){
            return HttpResult.fail("该订单已核销！");
        }
        if (dbOrder.getStatus()!=PayStatus.SUCCESS.value()){
            return HttpResult.fail("该订单当前状态不是支付成功！");
        }

        MotOrder reqOrder = new MotOrder();
        reqOrder.setMotNo(order.getMotNo());
        reqOrder.setStatus(3);
        reqOrder.setIsWriteOff(2);
        motOrderMapper.updateOrder(reqOrder);

        dbOrder.setStatus(3);
        dbOrder.setIsWriteOff(2);
        dbOrder.setCar(userCarMapper.getByCarId(dbOrder.getCarId()));
        dbOrder.setServiceContent(serviceContentMapper.getByServiceId(dbOrder.getServiceId()));
        dbOrder.setSiteInfo(siteMapper.getBySiteId(dbOrder.getSiteId()));

        //分佣
        commissionShare(dbOrder);
        //消息
        UserMessage message = new UserMessage();
        message.setMsgType(1);
        message.setOrderNo(order.getMotNo());
        message.setContent("您的车检服务已核销成功！");
        message.setUserId(dbOrder.getUserId());
        userMessageMapper.insert(message);
        return new HttpResult(dbOrder);
    }


    @Async
    public void commissionShare(MotOrder order) {

        UserInfo user = userMapper.getByUserId(order.getUserId());
        if (StringUtils.isEmpty(user.getParentUserId())) return;
        SiteServiceContent serviceContent = serviceContentMapper.getByServiceId(order.getServiceId());
        UserInfo secondUser = userMapper.getByUserId(user.getParentUserId());
        if (null!=serviceContent.getSecondCommission()&&secondUser.getUserType()==0){
            UserBalanceRecord balanceRecord = new UserBalanceRecord();
            balanceRecord.setBalance(serviceContent.getSecondCommission());
            balanceRecord.setUserId(secondUser.getUserId());
            balanceRecord.setRecordName("车检佣金分成");
            balanceRecord.setRecordType(1);
            balanceRecord.setOrderNo(order.getMotNo());
            balanceRecordMapper.insert(balanceRecord);
            BigDecimal num1 = new BigDecimal(new Double(secondUser.getBalance()).toString());
            BigDecimal num2 = new BigDecimal(new Double(serviceContent.getSecondCommission()).toString());
            secondUser.setBalance(num1.add(num2).doubleValue());
            userMapper.updateBalance(secondUser);
        }
        if (StringUtils.isEmpty(secondUser.getParentUserId())||null==serviceContent.getFirstCommission()) return;
        UserInfo firstUser = userMapper.getByUserId(secondUser.getParentUserId());
        if (firstUser.getUserType()==1) return;
        UserBalanceRecord balanceRecord = new UserBalanceRecord();
        balanceRecord.setBalance(serviceContent.getFirstCommission());
        balanceRecord.setUserId(firstUser.getUserId());
        balanceRecord.setRecordName("车检佣金分成");
        balanceRecord.setRecordType(1);
        balanceRecord.setOrderNo(order.getMotNo());
        balanceRecordMapper.insert(balanceRecord);
        BigDecimal num1 = new BigDecimal(new Double(firstUser.getBalance()).toString());
        BigDecimal num2 = new BigDecimal(new Double(serviceContent.getSecondCommission()).toString());
        firstUser.setBalance(num1.add(num2).doubleValue());
        userMapper.updateBalance(firstUser);
    }


    @Override
    public HttpResult motRefundMoney(ComposeCommitDto qto) {
        MotOrder motOrder = motOrderMapper.getByMotNo(qto.getMotNo());
        Double cancelPickUpFee = Double.valueOf(sysConfigMapper.getByKey(SysConstants.CANCEL_PICK_UP_FEE).getConfigValue());
        if (cancelPickUpFee>motOrder.getActualPay()){
            return HttpResult.fail("订单金额不足以扣减接车服务费！");
        }
        Double cancelFee =cancelPickUpFee*100;

        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
        refundRequest.setOutTradeNo(qto.getMotNo());
        refundRequest.setOutRefundNo(qto.getMotNo());
        //订单总金额
        Integer totalFee = BaseWxPayRequest.yuanToFen(motOrder.getActualPay().toString());
        Integer refundFee = BaseWxPayRequest.yuanToFen(motOrder.getActualPay().toString());
        if (qto.getIsArrival()==1){
            refundFee = refundFee-cancelFee.intValue();
        }

        refundRequest.setTotalFee(totalFee);
        refundRequest.setRefundFee(refundFee);
        refundRequest.setNotifyUrl(backMotNotifyUrl);
        try {
            WxPayRefundResult refund = wxService.refund(refundRequest);
            log.info("车检订单退款返回：{}",refund);
            return HttpResult.OK;
        }catch (Exception e){
            e.printStackTrace();
        }
        return HttpResult.fail("退款失败！");
    }

    @Override
    public HttpResult motReservationPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(MotReservation.class);
        List<MotReservation> list = reservationMapper.list(null,qto.getSiteId(),qto.getStatus());
        for (MotReservation order:list){
            order.setCar(userCarMapper.getByCarId(order.getCarId()));
            order.setSiteInfo(siteMapper.getBySiteId(order.getSiteId()));
        }
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult completeMotReservation(MotReservation order) {

        MotReservation reqOrder = new MotReservation();
        reqOrder.setReservationNo(order.getReservationNo());
        reqOrder.setStatus(1);
        reservationMapper.updateStatus(reqOrder);
        return HttpResult.OK;
    }

    @Override
    public HttpResult shoppingOrderPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingOrder.class);
        List<ShoppingOrder> list = shoppingOrderMapper.sysList(qto.getIsShip(), qto.getPayStatus(),qto.getOrderType(),qto.getPayType(),qto.getPayTimeStart(),qto.getPayTimeEnd());
        for (ShoppingOrder order :list){
            if (StringUtils.isNotEmpty(order.getReceiverAddrId())){
                ReceivingAddrInfo addrInfo = addrInfoMapper.getByReceivingAddrId(order.getReceiverAddrId());
                order.setReceivingAddrInfo(addrInfo);
            }
        }
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult shoppingOrderDetail(ShoppingOrder order) {
        List<ShoppingOrderDetail> details = shoppingOrderMapper.orderDetail(order.getOrderNo());
        return new HttpResult(details);
    }

    @Override
    public HttpResult shoppingRefundOrderPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingRefundOrder.class);
        List<ShoppingRefundOrder> list = shoppingRefundOrderMapper.sysList(qto.getRefundStatus(),qto.getOrderNo(),qto.getRefundNo(),qto.getCreateTimeStart(),qto.getCreateTimeEnd());
        page.setResult(list);
        return new HttpResult(page);
    }



    @Override
    public HttpResult shoppingChangeOrderPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingChangeOrder.class);
        List<ShoppingChangeOrder> list = changeOrderMapper.sysList(qto.getChangeStatus(),qto.getOrderNo(),qto.getChangeNo(),qto.getCreateTimeStart(),qto.getCreateTimeEnd());
        for (ShoppingChangeOrder changeOrder:list){
            changeOrder.setSku(shoppingSkuMapper.getBySkuId(changeOrder.getSkuId()));
            changeOrder.setNewSku(shoppingSkuMapper.getBySkuId(changeOrder.getNewSkuId()));
        }
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult withdrawalPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserWithdrawalRecord.class);
        List<UserWithdrawalRecord> list = withdrawalRecordMapper.list(null);
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult firstAidPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(CarFirstAid.class);
        List<CarFirstAid> list = carFirstAidMapper.selectAll();
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult addCarLogo(CarLogo logo) {
        carDefaultImgMapper.insertLogo(logo);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteCarLogo(CarLogo logo) {
        carDefaultImgMapper.deleteLogo(logo.getId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult carLogoPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(CarLogo.class);
        List<CarLogo> list = carDefaultImgMapper.logoList(qto.getKeyword());
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult userBalancePage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserBalanceRecord.class);
        List<UserBalanceRecord> list = balanceRecordMapper.sysList(qto.getRecordType(), qto.getNickName(), qto.getPhone(),
                qto.getCreateTimeStart(),qto.getCreateTimeEnd());
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult addCarImg(CarDefaultImg logo) {
        carDefaultImgMapper.insert(logo);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteCarImg(CarDefaultImg logo) {
        carDefaultImgMapper.deleteByPrimaryKey(logo.getId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult carImgPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(CarDefaultImg.class);
        List<CarDefaultImg> list = carDefaultImgMapper.selectAll(qto.getKeyword());
        page.setResult(list);
        return new HttpResult(page);
    }




    @Override
    public HttpResult updateWithdrawalStatus(UserWithdrawalRecord withdrawalRecord) {

        withdrawalRecordMapper.updateStatus(withdrawalRecord);
        //如果是成功 生成一笔佣金扣减
        if (withdrawalRecord.getStatus()==2){
            UserWithdrawalRecord record =  withdrawalRecordMapper.getById(withdrawalRecord.getWithdrawalId());
            UserInfo user =  userMapper.getByUserId(record.getUserId());
            UserBalanceRecord balanceRecord = new UserBalanceRecord();
            balanceRecord.setBalance(record.getWithdrawalMoney());
            balanceRecord.setUserId(record.getUserId());
            balanceRecord.setRecordName("佣金提现");
            balanceRecord.setRecordType(2);
            balanceRecord.setOrderNo(record.getWithdrawalId());
            balanceRecordMapper.insert(balanceRecord);
            //扣减佣金
            BigDecimal num1 = new BigDecimal(new Double(user.getBalance()).toString());
            BigDecimal num2 = new BigDecimal(new Double(record.getWithdrawalMoney()).toString());
            user.setBalance(num1.subtract(num2).doubleValue());
            userMapper.updateBalance(user);
        }
        return HttpResult.OK;
    }

//    @Override
//    public HttpResult acceptedShoppingChangeOrder(ComposeCommitDto qto) {
//        ShoppingChangeOrder changeOrder = changeOrderMapper.getByChangeNo(qto.getChangeNo());
//        if (null==changeOrder){
//            return HttpResult.fail("未查询到相关换货记录！");
//        }
//        if (changeOrder.getChangeStatus()!= ChangeStatus.INIT.value()){
//            return HttpResult.fail("换货记录状态有误！");
//        }
//        changeOrder.setChangeStatus(ChangeStatus.ACCEPTED.value());
//        changeOrderMapper.update(changeOrder);
//
//        //消息
//        UserMessage message = new UserMessage();
//        message.setMsgType(3);
//        message.setOrderNo(qto.getOrderNo());
//        message.setContent("您的换货申请已通过！");
//        message.setUserId(changeOrder.getUserId());
//        userMessageMapper.insert(message);
//        return HttpResult.OK;
//    }

//    @Override
//    public HttpResult refuseedShoppingChangeOrder(ComposeCommitDto qto) {
//        ShoppingChangeOrder changeOrder = changeOrderMapper.getByChangeNo(qto.getChangeNo());
//        if (null==changeOrder){
//            return HttpResult.fail("未查询到相关换货记录！");
//        }
//        if (changeOrder.getChangeStatus()!= ChangeStatus.INIT.value()){
//            return HttpResult.fail("换货记录状态有误！");
//        }
//        changeOrder.setChangeStatus(ChangeStatus.REFUSED.value());
//        changeOrderMapper.update(changeOrder);
//
//        //消息
//        UserMessage message = new UserMessage();
//        message.setMsgType(3);
//        message.setOrderNo(qto.getOrderNo());
//        message.setContent("您的换货申请已被拒绝！");
//        message.setUserId(changeOrder.getUserId());
//        userMessageMapper.insert(message);
//        return HttpResult.OK;
//    }


//    @Override
//    public HttpResult confirmShoppingChangeOrder(ComposeCommitDto qto) {
//        ShoppingChangeOrder changeOrder = changeOrderMapper.getByChangeNo(qto.getChangeNo());
//        if (null==changeOrder){
//            return HttpResult.fail("未查询到相关换货记录！");
//        }
//        if (changeOrder.getChangeStatus()!= ChangeStatus.RETURNED.value()){
//            return HttpResult.fail("换货记录状态有误！");
//        }
//        changeOrder.setChangeStatus(ChangeStatus.RECEIVED.value());
//        changeOrderMapper.update(changeOrder);
//        return HttpResult.OK;
//    }

    @Override
    public HttpResult fillInShoppingChangeOrder(ShoppingChangeOrder changeOrder) {
        changeOrder.setChangeStatus(ChangeStatus.SENDED.value());
        changeOrder.setShippingTime(new Date());
        changeOrderMapper.update(changeOrder);

        ShoppingChangeOrder byChangeNo = changeOrderMapper.getByChangeNo(changeOrder.getChangeNo());

        ShoppingOrderDetail detail = shoppingOrderDetailMapper.getDetail(byChangeNo.getOrderNo(),byChangeNo.getSkuId());
        detail.setStatus(ShoppingStatus.CHANGE_SEND.value());
        shoppingOrderDetailMapper.updateStatus(detail);
        return HttpResult.OK;
    }

    @Override
    public HttpResult acceptedShoppingRefundOrder(ComposeQueryDto qto) {
        ShoppingRefundOrder refundOrder = shoppingRefundOrderMapper.getByRefundNo(qto.getRefundNo());
        if (null==refundOrder){
            return HttpResult.fail("未查询到相关订单！");
        }
        if (refundOrder.getRefundStatus()!= RefundStatus.INIT.value()){
            return HttpResult.fail("订单状态有误！");
        }
        refundOrder.setRefundStatus(RefundStatus.ACCEPTED.value());
        shoppingRefundOrderMapper.update(refundOrder);

        //消息
        UserMessage message = new UserMessage();
        message.setMsgType(3);
        message.setOrderNo(qto.getOrderNo());
        message.setContent("您的退款申请已通过！");
        message.setUserId(refundOrder.getUserId());
        userMessageMapper.insert(message);
        return HttpResult.OK;
    }


    @Override
    public HttpResult refuseShoppingRefundOrder(ComposeQueryDto qto) {

        ShoppingRefundOrder dbRefundOrder = shoppingRefundOrderMapper.getByRefundNo(qto.getRefundNo());
        dbRefundOrder.setRefundStatus(RefundStatus.REFUSED.value());
        shoppingRefundOrderMapper.update(dbRefundOrder);
        //通过订单号查询商品id
        ShoppingOrderDetail detail = shoppingOrderDetailMapper.getDetail(dbRefundOrder.getOrderNo(),dbRefundOrder.getSkuId());
        //修改订单状态
        detail.setStatus(ShoppingStatus.REFUND_REFUSED.value());

        shoppingOrderDetailMapper.updateStatus(detail);

        //消息
        UserMessage message = new UserMessage();
        message.setMsgType(3);
        message.setOrderNo(qto.getOrderNo());
        message.setContent("您的退款申请已被商家拒绝！");
        message.setUserId(dbRefundOrder.getUserId());
        userMessageMapper.insert(message);
        return HttpResult.OK;

    }

    //确认退款
    @Override
    public HttpResult refundShoppingMoney(ComposeQueryDto qto) {
        ShoppingRefundOrder refundOrder = shoppingRefundOrderMapper.getByRefundNo(qto.getRefundNo());
        if (null==refundOrder){
            return HttpResult.fail("未查询到相关订单！");
        }
        if (refundOrder.getRefundStatus()!= RefundStatus.RETURNED.value()){
            return HttpResult.fail("订单状态有误！");
        }
        if (refundOrder.getRefundFee()< qto.getRefundMoney()){
            return HttpResult.fail("退款金额大于订单金额！");
        }
        //查看支付方式
        ShoppingOrder order = shoppingOrderMapper.getByOrderNo(refundOrder.getOrderNo());
        if (order.getPayType()==PayType.BALANCE.value()){
            UserBalanceRecord balanceRecord = new UserBalanceRecord();
            balanceRecord.setBalance(qto.getRefundMoney());
            balanceRecord.setUserId(order.getUserId());
            balanceRecord.setRecordName("商城退还佣金");
            balanceRecord.setRecordType(1);
            balanceRecord.setOrderNo(refundOrder.getOrderNo());
            balanceRecordMapper.insert(balanceRecord);
            UserInfo user = userMapper.getByUserId(order.getUserId());
            user.setBalance(BigDecimalUtil.add(user.getBalance(),balanceRecord.getBalance()).doubleValue());
            userMapper.updateBalance(user);
            refundOrder.setRefundStatus(RefundStatus.SUCCESS.value());
            refundOrder.setRefundTime(new Date());
            refundOrder.setSettlementRefundFee(BaseWxPayRequest.yuanToFen(qto.getRefundMoney().toString()));
            shoppingRefundOrderMapper.update(refundOrder);
            ShoppingOrderDetail detail = shoppingOrderDetailMapper.getDetail(refundOrder.getOrderNo(), refundOrder.getSkuId());
            detail.setStatus(ShoppingStatus.REFUND_SUCCESS.value());
            shoppingOrderDetailMapper.updateStatus(detail);
            return HttpResult.OK;
        }else if (order.getPayType()==PayType.WXPAY.value()){
            WxPayRefundRequest refundRequest = new WxPayRefundRequest();
            refundRequest.setOutTradeNo(refundOrder.getOrderNo());
            refundRequest.setOutRefundNo(qto.getRefundNo());
            refundRequest.setTotalFee(refundOrder.getTotalFee());
            refundRequest.setRefundFee(BaseWxPayRequest.yuanToFen(qto.getRefundMoney().toString()));
            refundRequest.setNotifyUrl(backShoppingNotifyUrl);
            try {
                WxPayRefundResult refund = wxService.refund(refundRequest);
                log.info("退款返回：{}",refund);
            }catch (Exception e){
                e.printStackTrace();
            }
            refundOrder.setRefundStatus(RefundStatus.REFUNDING.value());
            shoppingRefundOrderMapper.update(refundOrder);
            return HttpResult.OK;
        }else{
            return HttpResult.fail("只有余额支付和微信支付支持退款！");
        }

    }



    @Override
    public HttpResult distributeOrder(ComposeQueryDto qto) {
        shoppingOrderMapper.distributeOrder(qto.getOrderNo(),qto.getSkuId(),qto.getShippingName(),qto.getShippingCode(),qto.getDeliveryTime());
        ShoppingOrderDetail dbdetail = shoppingOrderDetailMapper.getDetail(qto.getOrderNo(),qto.getSkuId());
        dbdetail.setStatus(ShoppingStatus.TRANSPORT.value());
        shoppingOrderDetailMapper.updateStatus(dbdetail);
//        //是否该订单下都已发货
//        boolean isShip = true;
//        List<ShoppingOrderDetail> details = shoppingOrderDetailMapper.getByOrderNo(qto.getOrderNo());
//        for (ShoppingOrderDetail detail:details){
//            if (!detail.getSpuId().equals(qto.getSkuId())){
//                if (StringUtils.isEmpty(detail.getShippingCode())){
//                    isShip = false;
//                }
//            }
//        }
//        if (isShip){
//            shoppingOrderMapper.setShip(qto.getOrderNo());
//            //修改订单状态
//            ShoppingOrder order = new ShoppingOrder();
//            order.setOrderNo(qto.getOrderNo());
//            order.setPayStatus(ShoppingStatus.TRANSPORT.value());
//            shoppingOrderMapper.updateStatus(order);
//        }
        return HttpResult.OK;
    }


    @Override
    public HttpResult customPage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserInfo.class);
        List<UserInfo> list = userMapper.list(qto.getNickName(),qto.getPhone(),qto.getEmail(),qto.getUserType(),qto.getStatus());
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult getCustomNext(ComposeQueryDto queryDto) {
        String userId = queryDto.getUserId();
        Page page = queryDto.getPage();
        page.initPagingData(UserInfo.class);
        List<UserInfo> nextUsers = userMapper.getByParentUserId(userId);
        page.setResult(nextUsers);
        return new HttpResult(page);
    }

    @Override
    public HttpResult getCustomCar(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserCar.class);
        String userId = qto.getUserId();
        List<UserCar> list = userCarMapper.myCar(userId,qto.getIsDefault());
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult setUserType(UserInfo info) {
        userMapper.setUserType(info);
        return HttpResult.OK;
    }


    @Override
    public HttpResult getAchievement(ComposeQueryDto info) {

        String userId = info.getUserId();
        List<UserInfo> next1 = userMapper.getByParentUserId(userId);
        for (UserInfo user1:next1){
            List<MotOrder> order1 = motOrderMapper.getByUserId(user1.getUserId(),MotOrderStatus.COMPLETED.value(),info.getPayTimeStart(),info.getPayTimeEnd());
            user1.setMotOrders(order1);
            List<UserInfo> next2 = userMapper.getByParentUserId(user1.getUserId());
            for (UserInfo user2:next2){
                List<MotOrder> order2 = motOrderMapper.getByUserId(user2.getUserId(),MotOrderStatus.COMPLETED.value(),info.getPayTimeStart(),info.getPayTimeEnd());
                user2.setMotOrders(order2);
            }
        }
        return new HttpResult(next1);
    }

    @Override
    public HttpResult sendPoint(SendDto dto) {

        for (String userId:dto.getUserIds()) {
            UserPointsRecord pointsRecord =new UserPointsRecord();
            pointsRecord.setRecordName("赠送积分");
            pointsRecord.setUserId(userId);
            pointsRecord.setPoint(dto.getPoint());
            pointsRecord.setRemainingPoint(dto.getPoint());
            pointsRecord.setValidityDate(dto.getValidityDate());
            pointsRecord.setRecordType(1);
            pointsRecord.setStatus(1);
            pointRecordMapper.insert(pointsRecord);
        }
        return HttpResult.OK;
    }

    @Override
    public HttpResult sendCoupon(SendDto dto) {
        CouponInfo coupon = couponMapper.getByCouponId(dto.getCouponId());
        for (String userId:dto.getUserIds()) {
            UserCouponRecord couponRecord =new UserCouponRecord();
            String couponRecordId = UUID.randomUUID().toString().replaceAll("-", "");
            couponRecord.setCouponId(dto.getCouponId());
            couponRecord.setUserId(userId);
            couponRecord.setCouponRecordId(couponRecordId);
            couponRecord.setValidityDate(DateUtils.add(new Date(), Calendar.DATE, coupon.getValidityDay()));
            couponRecordMapper.insert(couponRecord);
        }
        return HttpResult.OK;
    }

    @Override
    public HttpResult sendCouponToAllCustom(SendDto dto) {
        sendCouponAllCustom(dto);
        return HttpResult.OK;
    }

    @Async
    public HttpResult sendCouponAllCustom(SendDto dto) {
        CouponInfo coupon = couponMapper.getByCouponId(dto.getCouponId());
        List<UserInfo> list = userMapper.list(null, null, null, null, null);
        for (UserInfo user:list) {
            UserCouponRecord couponRecord =new UserCouponRecord();
            String couponRecordId = UUID.randomUUID().toString().replaceAll("-", "");
            couponRecord.setCouponId(dto.getCouponId());
            couponRecord.setUserId(user.getUserId());
            couponRecord.setCouponRecordId(couponRecordId);
            couponRecord.setValidityDate(DateUtils.add(new Date(), Calendar.DATE, coupon.getValidityDay()));
            couponRecordMapper.insert(couponRecord);
        }
        return HttpResult.OK;
    }

    @Override
    public HttpResult sendBalance(SendDto dto) {
        for (String userId:dto.getUserIds()) {
            UserInfo user = userMapper.getByUserId(userId);
            user.setBalance(BigDecimalUtil.add(user.getBalance(),dto.getBalance()).doubleValue());
            userMapper.updateBalance(user);
            user.setAccrueExpend(BigDecimalUtil.add(user.getAccrueExpend(),dto.getBalance()).doubleValue());
            userMapper.updateAccrueExpend(user);
        }
        return HttpResult.OK;
    }





    @Override
    public HttpResult advertPage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(AdvertisementInfo.class);
        List<AdvertisementInfo> cartList = advertisementInfoMapper.advertList(qto.getAdType());
        page.setResult(cartList);
        return new HttpResult(page);
    }

    @Override
    public HttpResult addAdvert( AdvertisementInfo advert) {
        if(advert.getAdType()==AdvertType.SCLC.value()
                ||advert.getAdType()==AdvertType.TGHB.value()
                ||advert.getAdType()==AdvertType.NJXZ.value()
                ||advert.getAdType()==AdvertType.TXSM.value()
                ||advert.getAdType()==AdvertType.FWXY.value()
                ||advert.getAdType()==AdvertType.BXJS.value()
        ){
            return HttpResult.fail("该类型只允许存在一条记录！");
        }
        advertisementInfoMapper.insert(advert);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteAdvert( AdvertisementInfo advert) {
        AdvertisementInfo byId = advertisementInfoMapper.getById(advert.getId());
        if(advert.getAdType()==AdvertType.SCLC.value()
                ||advert.getAdType()==AdvertType.TGHB.value()
                ||advert.getAdType()==AdvertType.NJXZ.value()
                ||advert.getAdType()==AdvertType.TXSM.value()
                ||advert.getAdType()==AdvertType.FWXY.value()
                ||advert.getAdType()==AdvertType.BXJS.value()
        ){
            return HttpResult.fail("该类型必须存在一条记录！");
        }
        advertisementInfoMapper.delete(advert.getId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateAdvert( AdvertisementInfo record) {
        advertisementInfoMapper.update(record);
        return HttpResult.OK;
    }



    @Override
    public HttpResult sitePage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(SiteInfo.class);
        List<SiteInfo> roomList = siteMapper.sysList(qto.getSiteType(),qto.getKeyword());
        page.setResult(roomList);
        return new HttpResult(page);
    }

    @Override
    public HttpResult addSite(  SiteInfo room) {
        String siteId = IdUtil.uuid();
        room.setSiteId(siteId);
        siteMapper.insert(room);
        return HttpResult.OK;
    }




    @Override
    public HttpResult deleteSite(  SiteInfo siteInfo) {
        siteMapper.delete(siteInfo.getSiteId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateSite(  SiteInfo siteInfo) {
        siteMapper.updateBySiteId(siteInfo);
        return HttpResult.OK;
    }



    @Override
    public HttpResult siteServiceContentPage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(SiteServiceContent.class);
        List<SiteServiceContent> roomList = serviceContentMapper.selectAll(qto.getSiteId());
        page.setResult(roomList);
        return new HttpResult(page);
    }

    @Override
    public HttpResult addSiteServiceContent(  SiteServiceContent serviceContent) {
        String serviceId = IdUtil.uuid();
        serviceContent.setServiceId(serviceId);
        serviceContentMapper.insert(serviceContent);
        //生成可预订记录
        handleServicePredetermine(serviceContent);
        return HttpResult.OK;
    }

    @Async
    public void handleServicePredetermine(SiteServiceContent serviceContent){
        try {
            String serviceId = serviceContent.getServiceId();
            Integer timeLimit = serviceContent.getTimeLimit();
            Date nowDate = DateUtils.getNowDate();
            Date maxDate =null;
            //获取已生成记录的最大日期
            String maxDateStr = predetermineRecordMapper.getMaxDate(serviceId);
            int datePoordDay = 0;
            if (StringUtils.isEmpty(maxDateStr)){
                maxDate = nowDate;
            }else{
                maxDate = DateUtils.formatToDate(maxDateStr);
                datePoordDay = DateUtils.getDatePoordDay(maxDate, nowDate)+1;
            }

            if (maxDate.getTime()>=DateUtils.add(nowDate, Calendar.DATE, 6).getTime()){
                return;
            }

            Integer satOnline = serviceContent.getSatOnline();
            Integer sunOnline = serviceContent.getSunOnline();
            Integer holidayOnline = serviceContent.getHolidayOnline();

            for (int day = 0; day < 7-datePoordDay; day++) {
                LocalTime timeRangeStart = serviceContent.getTimeRangeStart();
                LocalTime timeRangeEnd = serviceContent.getTimeRangeEnd();
                Date date = DateUtils.add(nowDate, Calendar.DATE, datePoordDay + day);
                String workingDay = HolidayUtil.isWorkingDay(DateUtils.formatD(date));
                if (workingDay.equals("2")&&sunOnline==0){
                    continue;
                }
                if (workingDay.equals("1")&&satOnline==0){
                    continue;
                }
                if (workingDay.equals("2")&&sunOnline==1){
                    timeRangeStart = serviceContent.getSunTimeRangeStart();
                    timeRangeEnd = serviceContent.getSunTimeRangeEnd();
                }else if (workingDay.equals("1")&&satOnline==1){
                    timeRangeStart = serviceContent.getSatTimeRangeStart();
                    timeRangeEnd = serviceContent.getSatTimeRangeEnd();
                }
                long minutesBetween = ChronoUnit.MINUTES.between(timeRangeStart, timeRangeEnd);
                //应该有多少条记录
                int dif = (int) Math.floor(minutesBetween / timeLimit);
                LocalTime nextRecordTime = timeRangeStart.plusMinutes(0);
                for (int i = 1; i <= dif+2; i++) {
                    if (nextRecordTime.isBefore(timeRangeEnd)) {
                        System.out.println("Creating record at: " + nextRecordTime);
                        SiteServicePredetermineRecord predetermineRecord = new SiteServicePredetermineRecord();
                        String predetermineId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
                        predetermineRecord.setPredetermineId(predetermineId);
                        predetermineRecord.setServiceId(serviceId);
                        predetermineRecord.setPredetermineDate(date);
                        predetermineRecord.setPredetermineTime(nextRecordTime);
                        predetermineRecord.setTotalCount(serviceContent.getTotalCount());
                        predetermineRecord.setPredetermineCount(0);

                        if (workingDay.equals("3")&&holidayOnline==0){
                            predetermineRecord.setStatus(0);
                        }else if (workingDay.equals("2")&&sunOnline==0){
                            predetermineRecord.setStatus(0);
                        }else if (workingDay.equals("1")&&satOnline==0){
                            predetermineRecord.setStatus(0);
                        }else{
                            predetermineRecord.setStatus(1);
                        }
                        predetermineRecordMapper.insert(predetermineRecord);
                        nextRecordTime = timeRangeStart.plusMinutes(timeLimit*i);
                    }
                }
            }
        } catch (Exception e) {
            log.error("SystemTask.handleRoomPredetermine() error",e);
        }
    }



    @Override
    public HttpResult deleteSiteServiceContent(  SiteServiceContent siteInfo) {
        serviceContentMapper.delete(siteInfo.getServiceId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateSiteServiceContent(  SiteServiceContent siteInfo) {
        serviceContentMapper.update(siteInfo);
        return HttpResult.OK;
    }


    @Override
    public HttpResult deleteCarType(SysCarType carType) {
        carTypeMapper.deleteByPrimaryKey(carType.getId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult addCarType(SysCarType carType) {
        carTypeMapper.insert(carType);
        return HttpResult.OK;
    }


    @Override
    public HttpResult sysConfigList() {
        List<SysConfig> list = sysConfigMapper.selectAll();
        return new HttpResult(list);
    }

    @Override
    public HttpResult getConfig(SysConfig config) {
        SysConfig config1 = sysConfigMapper.getByKey(config.getConfigKey());
        return new HttpResult(config1);
    }



    @Override
    public HttpResult updateConfig(SysConfig config) {
        sysConfigMapper.updateConfig(config);
        return HttpResult.OK;
    }

    @Override
    public HttpResult switchList() {
        List<SysSwitch> list = sysUserMapper.switchList();
        return new HttpResult(list);
    }

    @Override
    public HttpResult switchOpen(SysSwitch sysSwitch) {
        sysUserMapper.handleswitch(sysSwitch.getCode(),0);
        return HttpResult.OK;
    }

    @Override
    public HttpResult switchClose(SysSwitch sysSwitch) {
        sysUserMapper.handleswitch(sysSwitch.getCode(),-1);
        return HttpResult.OK;
    }



    @Override
    public HttpResult updateShoppingSpuType(ShoppingSpuType spuType) {
        shoppingSpuTypeMapper.updateByPrimaryKey(spuType);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteShoppingSpuType(ShoppingSpuType spuType) {
        shoppingSpuTypeMapper.deleteByPrimaryKey(spuType.getId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult addShoppingSpuType(ShoppingSpuType spuType) {
        shoppingSpuTypeMapper.insert(spuType);
        return HttpResult.OK;
    }

    @Override
    public HttpResult shoppingSpuTypePage(ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingSpuType.class);
        List<ShoppingSpuType> list = shoppingSpuTypeMapper.selectAll();
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult shopLocation() {
        return new HttpResult(locationMapper.selectAll());
    }

    @Override
    public HttpResult setShopLocation(ShopLocation location) {

        ShopLocation dblocation = locationMapper.selectByPrimaryKey(location.getId());
        if (!dblocation.getAddress().equals(location.getAddress())){
            location.setAddress(location.getAddress().replace(location.getCity(),""));
            location.setAddress(location.getAddress().replace(location.getProvince(),""));
            location.setAddress(location.getAddress().replace(location.getCounty(),""));
            String lonAndLatByAddress = TiandituUtil.getLonAndLatByAddress(location.getProvince()
                    + location.getCity() + location.getCounty() + location.getAddress());
            location.setLongitudeLatitude(lonAndLatByAddress);
        }
        locationMapper.updateByPrimaryKey(location);
        return HttpResult.OK;
    }


    @Override
    public HttpResult exportMotOrder(ComposeQueryDto qto) {
        try {

            List<MotOrder> list = motOrderMapper.list(null,qto.getSiteId(),qto.getIsWriteOff(), qto.getMotType(),
                    qto.getStatus(),qto.getPayTimeStart(),qto.getPayTimeEnd(),qto.getSiteName());
            for (MotOrder order:list){
                order.setCar(userCarMapper.getByCarId(order.getCarId()));
                order.setServiceContent(serviceContentMapper.getByServiceId(order.getServiceId()));
                if (order.getStatus()==MotOrderStatus.SUCCESS.value()){
                    order.setStatusStr("支付成功");
                }
                if (order.getStatus()==MotOrderStatus.COMPLETED.value()){
                    order.setStatusStr("订单完成");
                }
                if (order.getStatus()==MotOrderStatus.FAIL.value()){
                    order.setStatusStr("支付失败");
                }
                if (order.getStatus()==MotOrderStatus.CANCEL.value()){
                    order.setStatusStr("已取消");
                }
                if (order.getStatus()==MotOrderStatus.WAIT_REFUND.value()){
                    order.setStatusStr("取消待退款");
                }

                if (order.getMotType()==1){
                    order.setMotTypeStr("到站服务");
                }
                if (order.getMotType()==2){
                    order.setMotTypeStr("上门接车");
                }
                order.setPayTimeStr(DateUtils.formatDT(order.getPayTime()));
                order.setPickUpTimeStr(DateUtils.formatDT(order.getPickUpTime()));
                order.setArrivalTimeStr(DateUtils.formatDT(order.getArrivalTime()));
            }
            final String[] exportField = { "motNo", "motTypeStr","statusStr","totalMoney","pickUpFee", "commission","discountMoney","actualPay","nickName","contactPhone","payTimeStr",
                    "siteName","serviceName","arrivalTimeStr","pickUpTimeStr","pickUpAdderss"};
            String path = execlUploadUtils.uploadExcelOss(null, FILE_PATH, "mot_order.xlsx", list,
                    AliOssUtil.SYS+"/excel/", "motOrder"+IdUtil.uuid()+".xlsx",
                    1, false, false, null, null, exportField);
            return new HttpResult(path);
        } catch (Exception e){
            log.error("EnterpriseExportServiceImpl.exportEnterpriseInfo() error", e);
            throw new BusinessException(e.getMessage());
        }
    }


    @Override
    public HttpResult exportBalance(ComposeQueryDto qto) {
        try {

            List<UserBalanceRecord> list = balanceRecordMapper.sysList(qto.getRecordType(), qto.getNickName(), qto.getPhone(),
                    qto.getCreateTimeStart(),qto.getCreateTimeEnd());
            for (UserBalanceRecord order:list){
                if (order.getRecordType()==1){
                    order.setRecordTypeStr("获得");
                }
                if (order.getRecordType()==2){
                    order.setRecordTypeStr("使用");
                }
                order.setCreateTimeStr(DateUtils.formatDT(order.getCreateTime()));
            }
            final String[] exportField = { "recordName", "recordTypeStr","balance","nickName","phone","createTimeStr"};
            String path = execlUploadUtils.uploadExcelOss(null, FILE_PATH, "commission.xlsx", list,
                    AliOssUtil.SYS+"/excel/", "commission"+IdUtil.uuid()+".xlsx",
                    1, false, false, null, null, exportField);
            return new HttpResult(path);
        } catch (Exception e){
            log.error("EnterpriseExportServiceImpl.exportEnterpriseInfo() error", e);
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public HttpResult exportShoppingOrder(ComposeQueryDto qto) {
        try {
            List<ShoppingOrder> list = shoppingOrderMapper.sysList(null,qto.getPayStatus(),qto.getOrderType(),qto.getPayType(),qto.getPayTimeStart(),qto.getPayTimeEnd());
            for (ShoppingOrder order:list){
                if (order.getPayStatus()==PayStatus.SUCCESS.value()){
                    order.setPayStatusStr("支付成功");
                }
                if (order.getPayStatus()==PayStatus.PAYING.value()){
                    order.setPayStatusStr("支付中");
                }
                if (order.getPayStatus()== PayStatus.FAIL.value()){
                    order.setPayStatusStr("支付失败");
                }
                if (order.getPayType()== PayType.BALANCE.value()){
                    order.setPayTypeStr("余额支付");
                }
                if (order.getPayType()== PayType.WXPAY.value()){
                    order.setPayTypeStr("微信支付");
                }
                if (order.getPayType()== PayType.POINT_PAY.value()){
                    order.setPayTypeStr("积分支付");
                }
                if (order.getIsShip()== 1){
                    order.setShipStr("未发货或部分发货");
                }
                if (order.getIsShip()== 2){
                    order.setShipStr("已全部发货");
                }

                if (null!=order.getReceiverAddrId()){
                    order.setReceiver("收件人："+order.getReceiver()+"|手机号："+order.getReceiverMobile()+"|收件地址："+order.getReceiverAddress());
                }
                order.setPayTimeStr(DateUtils.formatD(order.getPayTime()));
            }
            final String[] exportField = { "orderNo", "payStatusStr","totalMoney", "actualPay","discountStr","discountMoney","totalPoint",
                    "payTypeStr","nickName","phone", "payTimeStr","remark","receiver","shipStr"};
            String path = execlUploadUtils.uploadExcelOss(null, FILE_PATH, "shopping_order.xlsx", list,
                    AliOssUtil.SYS+"/excel/", "shoppingOrder"+IdUtil.uuid()+".xlsx",
                    1, false, false, null, null, exportField);
            return new HttpResult(path);
        } catch (Exception e){
            log.error("EnterpriseExportServiceImpl.exportEnterpriseInfo() error", e);
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public HttpResult exportShoppingRefundOrder(ComposeQueryDto qto) {
        try {
            List<ShoppingRefundOrder> list = shoppingRefundOrderMapper.sysList(qto.getRefundStatus(),qto.getOrderNo(),qto.getRefundNo(),qto.getCreateTimeStart(),qto.getCreateTimeEnd());
            for (ShoppingRefundOrder order:list){
                if (null!=order.getTotalFee()){
                    order.setTotalFee(order.getTotalFee()/100);
                }
                if (null!=order.getRefundFee()){
                    order.setRefundFee(order.getRefundFee()/100);
                }
                if (null!=order.getSettlementRefundFee()){
                    order.setSettlementRefundFee(order.getSettlementRefundFee()/100);
                }
                if (order.getRefundStatus()==RefundStatus.INIT.value()){
                    order.setRefundStatusStr("发起退款中");
                }
                if (order.getRefundStatus()==RefundStatus.SUCCESS.value()){
                    order.setRefundStatusStr("退款成功");
                }
                if (order.getRefundStatus()==RefundStatus.ACCEPTED.value()){
                    order.setRefundStatusStr("已受理");
                }
                if (order.getRefundStatus()==RefundStatus.RETURNED.value()){
                    order.setRefundStatusStr("商品已退回");
                }
                if (order.getRefundStatus()==RefundStatus.REFUNDING.value()){
                    order.setRefundStatusStr("退款中");
                }
                if (order.getRefundStatus()==RefundStatus.REFUSED.value()){
                    order.setRefundStatusStr("已拒绝");
                }
                if (order.getRefundStatus()==RefundStatus.CANCEL.value()){
                    order.setRefundStatusStr("已取消");
                }
                order.setRefundTimeStr(DateUtils.formatD(order.getRefundTime()));
            }
            final String[] exportField = { "orderNo", "refundNo","refundStatusStr","totalFee", "refundFee","settlementRefundFee","totalPoint",
                    "nickName","phone", "refundTimeStr","refundReason","shippingName","shippingCode"};
            String path = execlUploadUtils.uploadExcelOss(null, FILE_PATH, "refund_order.xlsx", list,
                    AliOssUtil.SYS+"/excel/", "shoppingRefundOrder"+IdUtil.uuid()+".xlsx",
                    1, false, false, null, null, exportField);
            return new HttpResult(path);
        } catch (Exception e){
            log.error("EnterpriseExportServiceImpl.exportEnterpriseInfo() error", e);
            throw new BusinessException(e.getMessage());
        }
    }

}
